/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.modular.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import vip.xiaonuo.core.consts.CommonConstant;
import vip.xiaonuo.core.context.login.LoginContextHolder;
import vip.xiaonuo.core.enums.CommonStatusEnum;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.pojo.login.SysLoginUser;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.core.util.PoiUtil;
import vip.xiaonuo.modular.system.entity.BizOrder;
import vip.xiaonuo.modular.system.entity.BizStock;
import vip.xiaonuo.modular.system.enums.BizOrderExceptionEnum;
import vip.xiaonuo.modular.system.mapper.BizOrderMapper;
import vip.xiaonuo.modular.system.param.BizOrderParam;
import vip.xiaonuo.modular.system.service.BizOrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.modular.system.service.BizStockService;
import vip.xiaonuo.modular.system.vo.BizOrderVO;
import vip.xiaonuo.modular.system.vo.BizStockVO;
import vip.xiaonuo.modular.system.vo.OrderDTO;
import vip.xiaonuo.sys.modular.user.entity.SysUser;
import vip.xiaonuo.sys.modular.user.service.SysUserService;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;

/**
 * 订单表service接口实现类
 *
 * @author can
 * @date 2022-03-19 14:11:47
 */
@Slf4j
@Service
public class BizOrderServiceImpl extends ServiceImpl<BizOrderMapper, BizOrder> implements BizOrderService {

    @Resource
    private BizStockService bizStockService;

    @Resource
    private SysUserService sysUserService;

    @Override
    public PageResult<BizOrderVO> page(BizOrderParam bizOrderParam) {
        QueryWrapper<BizOrder> queryWrapper = new QueryWrapper<>();
        Page<BizOrderVO> page;
        if (ObjectUtil.isNotNull(bizOrderParam)) {

            // 根据订单编号 查询
            if (ObjectUtil.isNotEmpty(bizOrderParam.getOrderCode())) {
                queryWrapper.lambda().eq(BizOrder::getOrderCode, bizOrderParam.getOrderCode());
            }
            Page<BizOrderVO> pageObj = new Page<>(PageFactory.defaultPage().getCurrent(), PageFactory.defaultPage().getSize());
            page = this.baseMapper.getPage(pageObj);
        } else {
            page = new Page<>();
        }
        return new PageResult<>(page);
    }

    @Override
    public List<BizOrder> list(BizOrderParam bizOrderParam) {
        return this.list();
    }

    @Override
    public void add(BizOrderParam bizOrderParam) {
        BizOrder bizOrder = new BizOrder();
        BeanUtil.copyProperties(bizOrderParam, bizOrder);
        this.save(bizOrder);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<BizOrderParam> bizOrderParamList) {
        bizOrderParamList.forEach(bizOrderParam -> {
            this.removeById(bizOrderParam.getId());
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(BizOrderParam bizOrderParam) {
        BizOrder bizOrder = this.queryBizOrder(bizOrderParam);
        BeanUtil.copyProperties(bizOrderParam, bizOrder);
        this.updateById(bizOrder);
    }

    @Override
    public BizOrder detail(BizOrderParam bizOrderParam) {
        return this.queryBizOrder(bizOrderParam);
    }

    /**
     * 获取订单表
     *
     * @author can
     * @date 2022-03-19 14:11:47
     */
    private BizOrder queryBizOrder(BizOrderParam bizOrderParam) {
        BizOrder bizOrder = this.getById(bizOrderParam.getId());
        if (ObjectUtil.isNull(bizOrder)) {
            throw new ServiceException(BizOrderExceptionEnum.NOT_EXIST);
        }
        return bizOrder;
    }

    @Override
    public void export(BizOrderParam bizOrderParam) {
        List<BizOrder> list = this.list(bizOrderParam);
        PoiUtil.exportExcelWithStream("SnowyBizOrder.xls", BizOrder.class, list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void order(OrderDTO po) {
        // 扣减库存
        log.info(JSON.toJSONString(po));

        BizStock stock = bizStockService.getById(po.getId());
        stock.setStockQty(stock.getStockQty() - po.getStockQty());
        bizStockService.updateById(stock);

        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
        SysUser user = sysUserService.getById(sysLoginUser.getId());

        // 创建订单
        BizOrder bizOrder = new BizOrder();
        bizOrder.setMatId(po.getMatId());
        bizOrder.setMatQty(po.getStockQty().longValue());
        bizOrder.setPrice(po.getPrice());
        bizOrder.setRemark(po.getRemark());
        // 默认创建订单备货中
        bizOrder.setStatus(1);
        bizOrder.setTargetPlace(user.getAddress());
        bizOrder.setOrderCode("DD" + this.getFixLenthString(8));
        bizOrder.setCreateUserId(sysLoginUser.getId());

        this.baseMapper.insert(bizOrder);
    }

    @Override
    public PageResult<BizOrderVO> pageUser(BizOrderParam bizOrderParam) {
        QueryWrapper<BizOrder> queryWrapper = new QueryWrapper<>();
        Page<BizOrderVO> page;
        if (ObjectUtil.isNotNull(bizOrderParam)) {

            // 根据订单编号 查询
            if (ObjectUtil.isNotEmpty(bizOrderParam.getOrderCode())) {
                queryWrapper.lambda().eq(BizOrder::getOrderCode, bizOrderParam.getOrderCode());
            }
            Page<BizOrderVO> pageObj = new Page<>(PageFactory.defaultPage().getCurrent(), PageFactory.defaultPage().getSize());
            SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
            page = this.baseMapper.getPageUser(pageObj, sysLoginUser.getId());
        } else {
            page = new Page<>();
        }
        return new PageResult<>(page);
    }

    /*
     * 返回长度为【strLength】的随机数，在前面补0
     */
    private String getFixLenthString(int strLength) {

        Random rm = new Random();

        // 获得随机数
        double pross = (1 + rm.nextDouble()) * Math.pow(10, strLength);

        // 将获得的获得随机数转化为字符串
        String fixLenthString = String.valueOf(pross);

        // 返回固定的长度的随机数
        return fixLenthString.substring(1, strLength + 1);
    }

}
